package com.yitiao.ratelimit;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class SlidingWindowRateLimiter {
    private final int windowSize; // 滑动窗口大小
    private final int rateLimit; // 限流阈值
    private final ConcurrentLinkedQueue<Long> timestamps; // 存储请求的时间戳
    private final AtomicInteger counter; // 计数器

    public SlidingWindowRateLimiter(int windowSize, int rateLimit) {
        this.windowSize = windowSize;
        this.rateLimit = rateLimit;
        this.timestamps = new ConcurrentLinkedQueue<>();
        this.counter = new AtomicInteger(0);
    }

    public boolean allowRequest() {
        long currentTime = System.currentTimeMillis();

        // 删除滑动窗口外的时间戳
        while (!timestamps.isEmpty() && timestamps.peek() <= currentTime - windowSize) {
            timestamps.poll();
            counter.decrementAndGet();
        }

        // 判断当前请求数是否超过限流阈值
        if (counter.incrementAndGet() <= rateLimit) {
            timestamps.offer(currentTime);
            return true; // 允许请求
        } else {
            counter.decrementAndGet();
            return false; // 拒绝请求
        }
    }
}
